<?php

namespace App\Api\System;

use PhalApi\Api;

/**
 * 获取公司部门
 * @desc 获取公司部门
 * @author: dogstar 2018-01-09
 */
class Dept extends Api
{
    public function getRules()
    {
        return array(
            'getList' => array(),
            'fixList' => array()
        );
    }


    /**
     * 获取公司部门
     * @desc 获取用户菜单
     * @return array 菜单数据
     */
    public function getList()
    {
        header('Access-Control-Allow-Origin:*');
        header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS');
        header('Access-Control-Allow-Headers:*');

        \PhalApi\DI()->response->addResult('success', true);
        $data = \PhalApi\DI()->notorm->admin_dept->fetchAll();
        return $data;
    }

    /**
     * 更新公司部门
     * @desc 根据id更新公司部门
     * @return array 操作结果
     */
    public function fixList()
    {
        header('Access-Control-Allow-Origin:*');
        header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS');
        header('Access-Control-Allow-Headers:*');

        $input = json_decode(file_get_contents('php://input'), true);
        if (empty($input)) {
            \PhalApi\DI()->response->addResult('error', '更新数据不能为空');
            return ['error' => '更新数据不能为空'];
        }

        if (empty($input['name'])) {
            \PhalApi\DI()->response->addResult('error', 'name不能为空');
            return ['error' => 'name不能为空'];
        }
        $id = $input['id'];

        $result = \PhalApi\DI()->notorm->admin_dept
            ->where('id', $id)
            ->update($input);

        if ($result === false) {
            \PhalApi\DI()->response->addResult('error', '更新失败');
            return ['error' => '更新失败'];
        }

        \PhalApi\DI()->response->addResult('success', true);
        return $result;
    }

    /**
     * 新增公司部门
     * @desc 新增公司部门
     * @return array 公司部门
     */
    public function addDept()
    {
        header('Access-Control-Allow-Origin:*');
        header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS');
        header('Access-Control-Allow-Headers:*');

        $input = json_decode(file_get_contents('php://input'), true);
        if (empty($input['name'])) {
            \PhalApi\DI()->response->addResult('error', 'name字段不能为空');
            return ['error' => 'name字段不能为空'];
        }

        $exists = \PhalApi\DI()->notorm->admin_dept->where('name', $input['name'])->fetchOne();
        if ($exists) {
            \PhalApi\DI()->response->addResult('error', $input['name']."已存在");
            return ['error' => 'name已存在'];
        }

        $input["create_time"] = date("Y-m-d H:i:s", time());
        $result = \PhalApi\DI()->notorm->admin_dept->insert($input);
        \PhalApi\DI()->response->addResult('success', true);
        return $result;
    }
}